package com.spring.arch.common.dto.result;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.Page;

import java.io.Serializable;

/**
 * 分页数据
 */
@NoArgsConstructor
@Getter
@Setter
public class PageDataDTO implements Serializable {
    private static final long serialVersionUID = 370809173454424686L;

    /**
     * 总条数
     */
    @ApiModelProperty(value = "总条数", position = 1)
    @JsonProperty(index = 1)
    private long totalElements;

    /**
     * 查询结果条数
     */
    @ApiModelProperty(value = "返回条数", position = 2)
    @JsonProperty(index = 2)
    private int numberOfElements;

    /**
     * 总页数
     */
    @ApiModelProperty(value = "总页数", position = 3)
    @JsonProperty(index = 3)
    private int totalPages;

    /**
     * 当前页码
     */
    @ApiModelProperty(value = "当前页码（从0开始）", position = 4)
    @JsonProperty(index = 4)
    private int number;

    /**
     * 是否第一页
     */
    @ApiModelProperty(value = "是否第一页", position = 5)
    @JsonProperty(index = 5)
    private boolean first;

    /**
     * 是否最后页
     */
    @ApiModelProperty(value = "是否最后页", position = 6)
    @JsonProperty(index = 6)
    private boolean last;

    /**
     * 页条数
     */
    @ApiModelProperty(value = "页条数", position = 7)
    @JsonProperty(index = 7)
    private int size;

    /**
     * 页开始行
     */
    @ApiModelProperty(value = "页开始行（相对于总记录数，从1开始计数）", position = 8)
    @JsonProperty(index = 8)
    public long getFromNumber() {
        if (this.numberOfElements == 0) {
            return (this.number * this.size);
        } else {
            return (this.number * this.size) + 1;
        }
    }

    /**
     * 页结束行
     */
    @ApiModelProperty(value = "本页结束行", position = 9)
    @JsonProperty(index = 9)
    public long getToNumber() {
        return (this.number * this.size) + this.numberOfElements;
    }

    /**
     * 转换对象
     */
    public static PageDataDTO valueOf(final Page<?> page) {
        final PageDataDTO pageData = new PageDataDTO();
        pageData.setFirst(page.isFirst());
        pageData.setLast(page.isLast());
        pageData.setNumber(page.getNumber());
        pageData.setTotalPages(page.getTotalPages());
        pageData.setNumberOfElements(page.getNumberOfElements());
        pageData.setSize(page.getSize());
        pageData.setTotalElements(page.getTotalElements());
        return pageData;
    }
}
